package main

import (
	"context"
	"fmt"
	"gateway-server/internal/config"
	"gateway-server/internal/middleware"
	"gateway-server/internal/registry"
	"gateway-server/internal/router"
	"gateway-server/internal/services"
	"gateway-server/pkg/beego"
	"log"
	"os"
)

const (
	DefaultConfigFile = "config/app.json"
	envConfigFile     = "CONFIG_FILE"
)

func main() {
	// 读取配置文件
	cgfFile := os.Getenv(envConfigFile)
	if cgfFile == "" {
		cgfFile = DefaultConfigFile
	}
	appConfig := config.LoadAppConfig(cgfFile)

	//初始化Etcd
	etcdRegistry, err := registry.NewEtcdRegistry(appConfig.Etcd.Endpoints)
	if err != nil {
		panic(err)
	}

	address := fmt.Sprintf("localhost:%d", appConfig.Server.HttpPort)

	// 创建网关服务
	gatewayService := services.Service{
		Name:     appConfig.Server.AppName,
		Registry: etcdRegistry,
		Address:  address,
	}
	// 注册网关服务到注册中心
	cancel, err := gatewayService.StartRegistration(context.Background(), &services.ServiceRegister{
		MaxRetries: 5,
		Services:   []services.Service{gatewayService},
	})
	if err != nil {
		log.Printf("服务注册失败: %v", err)
		if cancel != nil {
			cancel() // 安全释放资源
		}
		os.Exit(1) // 非正常退出码
	} else {
		log.Println("网关服务已成功注册到服务注册中心")
	}

	// 设置网关路由
	gatewayRouter := router.NewGatewayRouter()

	// 添加过滤中间件
	beego.InsertGlobalFilterChain(func(ctx *beego.BeeCtx, next beego.BeeNextFunc) {
		ctx.Request = ctx.Request.WithContext(context.WithValue(ctx.Request.Context(), registry.EtcdRegistryContextKey, etcdRegistry))
	})
	middleware.CORS()
	middleware.RequestLogger()
	middleware.UserAuth()

	gatewayRouter.Route()

	beego.Run(appConfig.Server.HttpPort)

}
